package com.vmove.childtrain.db.dao;

import android.content.Context;

import com.j256.ormlite.dao.Dao;
import com.vmove.childtrain.db.DatabaseHelper;
import com.vmove.childtrain.db.entity.Setting;

import java.sql.SQLException;
import java.util.List;
import java.util.Set;

public class SettingDao {
    private Context context;
    private Dao<Setting, Integer> settingDao;
    private DatabaseHelper helper;

    public SettingDao(Context context) {
        this.context = context;
        try {
            helper = DatabaseHelper.getHelper(context);
            settingDao = helper.getDao(Setting.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据设置名称查询设置项
     *
     * @param settingName
     * @return
     */
    public Setting getSettingByName(String settingName) {
        Setting setting = null;
        try {
            List<Setting> settings = settingDao.queryForEq(Setting.COLUMNNAME_NAME, settingName);
            if (null != settings && settings.size() > 0) {
                setting = settings.get(0);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return setting;
    }

    /**
     * 增加一个设置项目
     * @throws SQLException
     */
    public int addSetting(Setting setting) {
        Setting setting1 = getSettingByName(setting.getSettingName());
        try {
            if (null == setting1) {
                //配置项不存在，新增
                return settingDao.create(setting);
            } else {
                //配置项存在，修改
                setting1.setSettingValue(setting.getSettingValue());
                return settingDao.update(setting1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

}
